import {Modal, Form, Input, Upload, Button, Select, message} from 'antd'
import React, {useEffect} from "react";
import { apiInterceptors, createUser, updateUser, getUserById } from '@/client/api';
import {nameRule} from "../../../utils/validationRules";
const NodeRSA = require('node-rsa');
const UserModal = ({ handleType, isModalOpen, setModal, userId, successCall }:any) => {
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 14 },
    },
  };
  const [userForm] = Form.useForm();
  const submitHandle = async () => {
    try {
      const values = await userForm.validateFields();
      if (handleType === 'edit') {
        values.id = userId
        const [err] = await apiInterceptors(updateUser(values))
        if (!err) {
          message.success('操作成功')
        } else {
          return
        }
      }
      if (handleType === 'add') {
        console.log('Success:', values)
        const publicKey = `
          -----BEGIN PUBLIC KEY-----
            MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvjgRWo2jUU++5XPyme1+
            T0+RZ8W9LLEc1lDJNaREQm9CTcvVUbKvvK1bHi+vhSTlZwu8PaWj5YTuYRnAd9PX
            at5AFETSMFV79zEPHp5/JrxpcAu1d+u2Be5//keLkMGXTqDq75qcNZJI/Itlamfd
            s5KPrPngWbRR5xeE1wFj5ZisWb5dsqiw67saFa2xFxwLOm41ucXQ6vTzPKKtleaG
            myoMh+JPkOAsSMGig19WgOYbuhDAv1YZGOipp19MDKtdpZsL9a4sgeuYUAlnG05b
            QSVv4yzHRMDitngAXoLrErAACnIe6vsOspmMx1yeKzY5XEhvFYsoO0QWZXdk4hlV
            YQIDAQAB
          -----END PUBLIC KEY-----`

        const encrypt = new NodeRSA(publicKey);
        const password = encrypt.encrypt(values.password, 'base64')
        const [err] = await apiInterceptors(createUser({ ...values, password}))
        if (!err) {
          message.success('操作成功')
        } else {
          return
        }
      }
      setModal(false)
      resetForm()
      successCall()
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const cancelHandle = () => {
    setModal(false)
    resetForm()
  }
  const resetForm = () => {
    userForm.resetFields()
  }
  const getUserInfo = async () => {
    const [_, userInfo] = await apiInterceptors(getUserById(userId))
    userForm.setFieldsValue(userInfo)
  }
  useEffect(() => {
    if (handleType === 'edit') {
      getUserInfo()
    }
  },[])
  return (<>
    <Modal
      title={handleType === 'add' ? '新增用户' : '修改用户'}
      open={isModalOpen}
      onOk={submitHandle} onCancel={cancelHandle}
      width={600}
    >
      <Form {...formItemLayout} form={userForm}>
        <Form.Item label="用户名称" name="username" rules={[{ required: true, message: '请输入用户名称' }, nameRule]}>
          <Input />
        </Form.Item>
        {
          handleType === 'add' &&
          <Form.Item label="用户密码" name="password" rules={[{ required: true, message: '请输入用户密码' }]}>
            <Input.Password placeholder="" autoComplete='new-password' disabled={ handleType !== 'add' } />
          </Form.Item>
        }
        <Form.Item label="用户邮箱" name="email" rules={[{ required: true, message: '请输入用户邮箱' }, { type: 'email', message: '请输入正确的邮箱' }]}>
          <Input />
        </Form.Item>
        <Form.Item label="状态" name="is_active" rules={[{ required: true, message: '请选择状态' }]}>
          <Select
            placeholder="请选择状态"
            options={[
              { value: true, label: '启用' },
              { value: false, label: '禁用' },
            ]}
          />
        </Form.Item>
      </Form>
    </Modal>
  </>)
}

export default UserModal
